package com.niudong.esdemo.lucene;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.*;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;
import org.junit.After;
import org.junit.Test;

import java.io.File;
import java.net.InetAddress;
import java.nio.file.Paths;

public class demo01 {

    private IndexWriter indexWriter;
    private IndexReader indexReader;
    private IndexSearcher indexSearcher;


    private String path = "D:\\lucene\\data\\demo11";


    @After
    public void after() throws Exception {
        if (indexWriter!=null){
            indexWriter.commit();
            indexWriter.close();
        }
        if(indexReader != null){
            indexReader.close();
        }
    }

    public void search(Query query) throws Exception {

        // 搜索数据,两个参数：查询条件对象要查询的最大结果条数
        // 返回的结果是 按照匹配度排名得分前N名的文档信息（包含查询到的总条数信息、所有符合条件的文档的编号信息）。
        TopDocs topDocs = indexSearcher.search(query, 10);
        // 获取总条数
        System.out.println("本次搜索共找到" + topDocs.totalHits + "条数据");
        // 获取得分文档对象（ScoreDoc）数组.SocreDoc中包含：文档的编号、文档的得分
        ScoreDoc[] scoreDocs = topDocs.scoreDocs;

        for (ScoreDoc scoreDoc : scoreDocs) {
            // 取出文档编号
            int docID = scoreDoc.doc;
            // 根据编号去找文档
            Document doc = indexReader.document(docID);
            System.out.println("id: " + doc.get("id"));
            System.out.println("title: " + doc.get("title"));
            // 取出文档得分
            System.out.println("得分： " + scoreDoc.score);
        }
    }


    // 创建索引
    @Test
    public void testCreate() throws Exception {
        indexWriter =new IndexWriter(FSDirectory.open(Paths.get(path)),new IndexWriterConfig(new StandardAnalyzer()));


        for (int i = 0; i < 1000000; i++) {
            //1 创建文档对象
            Document document = new Document();
            // 创建并添加字段信息。参数：字段的名称、字段的值、是否存储，这里选Store.YES代表存储到文档列表。Store.NO代表不存储
            document.add(new TextField("id", String.valueOf(i), Field.Store.YES));
            //document.add(new TextField("time", String.valueOf(i), Field.Store.YES));
            document.add(new LongPoint("searchTime",i));
            document.add(new InetAddressPoint("InetAddressPoint", InetAddress.getByName("localhost")));


            // 这里我们title字段需要用TextField，即创建索引又会被分词。StringField会创建索引，但是不会被分词
            document.add(new TextField("title", "谷歌地图之父跳槽facebook" + i, Field.Store.YES));
            //6 把文档交给IndexWriter
            indexWriter.addDocument(document);
        }
    }


    @Test
    public void searchByTime() throws Exception {

        indexReader = DirectoryReader.open(FSDirectory.open(new File(path).toPath()));
        indexSearcher = new IndexSearcher(indexReader);
        searchByTime("searchTime",100L,200L);
    }

    public void searchByTime(String field, Long startTime, Long endTime) throws Exception {
        Query query = LongPoint.newRangeQuery(field,startTime,endTime);
        search(query);
    }
}
